package com.liu.seckill.exception;
import com.liu.seckill.vo.RespBean;
import com.liu.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName GlobalExceptionHandler
 * @Author ：name
 * @Date ：2022-02-15 9:46
 * @Description：
 * @Version: 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

     @ExceptionHandler(Exception.class)
  public RespBean ExceptionHandler(Exception e) {

         //pd左边对象是否是右边类的实例
         if(e instanceof GlobalException){//全局异常处理
             GlobalException ex = (GlobalException) e;
             log.info("全局异常:{}",ex.getRespBeanEnum());
             return  RespBean.error(ex.getRespBeanEnum());

         }else if (e instanceof BindException){//异常处理与参数校验

             BindException ex=(BindException) e;
             RespBean respBean=RespBean.error(RespBeanEnum.BIND_ERROR);
             log.info("全局异常:{}",ex.getBindingResult());
             respBean.setMessage("参数校验异常:"+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
             return respBean;
         }
         e.printStackTrace();
            return RespBean.error(RespBeanEnum.ERROR);
  }

}
